package com.dandelion.manager.system.web.controller;

import java.awt.image.BufferedImage;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

import com.dandelion.commons.SystemHelper;
import com.dandelion.commons.annotation.SystemLog;
import com.dandelion.commons.constants.BaseConst;
import com.dandelion.commons.spring.SpringContextHolder;
import com.dandelion.commons.web.controller.BaseController;
import com.dandelion.commons.web.model.AjaxResponse;
import com.dandelion.commons.web.model.DataGrid;
import com.dandelion.manager.system.domain.User;
import com.dandelion.manager.system.service.UserService;
import com.google.code.kaptcha.impl.DefaultKaptcha;

@Controller
@RequestMapping("/manager/system/user")
public class UserController extends BaseController {

	@Autowired
	public UserService service ;
	
	@Autowired
	private DefaultKaptcha captchaProducer;
	
	/**
	 * 主页
	 * @return
	 */
	@RequestMapping(value="/main", method=RequestMethod.GET)
	public String main() {
		return viewName("main") ;
	}
	
	/**
	 * 表单页面
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/form", method=RequestMethod.GET)
	public String form(Long id, Model model) {
		if(null != id) {
			model.addAttribute("id", id) ;
		}
		return viewName("form") ;
	}
	
	/**
	 * 添加
	 * @param dto
	 * @return
	 */
	@SystemLog(module=BaseConst.MODULE_SYSTEM+"[用户管理]", method="新增系统用户")
	@RequestMapping(value="/add", method=RequestMethod.POST)
	public @ResponseBody AjaxResponse add(User dto) {
		return this.service.add(dto);
	}
	
	/**
	 * 删除
	 * @param ids 数组
	 * @return
	 */
	@SystemLog(module=BaseConst.MODULE_SYSTEM+"[用户管理]", method="删除系统用户")
	@RequestMapping(value="/delete", method=RequestMethod.POST)
	public @ResponseBody AjaxResponse delete(Long[] ids) {
		return this.service.deleteBatch(ids);
	}
	
	/**
	 * 修改
	 * @param dto
	 * @return
	 */
	@SystemLog(module=BaseConst.MODULE_SYSTEM+"[用户管理]", method="修改系统用户")
	@RequestMapping(value="/update", method=RequestMethod.POST)
	public @ResponseBody AjaxResponse update(User dto) {
		return this.service.update(dto);
	}
	
	/**
	 * 根据ID获取数据
	 * @param id
	 * @return
	 */
	@SystemLog(module=BaseConst.MODULE_SYSTEM+"[用户管理]", method="加载系统用户")
	@RequestMapping(value="/get/{id}", method=RequestMethod.GET)
	public @ResponseBody User get(@PathVariable Long id) {
		return this.service.get(id) ;
	}
	
	/**
	 * 数据列表-分页查询
	 * @param dto
	 * @return
	 */
	@SystemLog(module=BaseConst.MODULE_SYSTEM+"[用户管理]", method="加载系统用户列表")
	@RequestMapping(value="/datagrid")
	public @ResponseBody DataGrid<User> datagrid(User dto) {
		return this.service.datagrid(dto) ;
	}
	
	/**
	 * 查询所有
	 * @param dto
	 * @return
	 */
	@SystemLog(module=BaseConst.MODULE_SYSTEM+"[用户管理]", method="查询所有系统用户")
	@RequestMapping(value="/getAllList")
	public @ResponseBody List<User> getAllList(User dto) {
		return this.service.getAllList(dto) ;
	}
	
	/**
	 * 用户账户状态编辑页面
	 * @return
	 */
	@RequestMapping(value="/user_locked", method=RequestMethod.GET)
	public String user_locked() {
		return viewName("user_locked") ;
	}
	/**
	 * 用户编辑状态页面
	 * @return
	 */
	@RequestMapping(value="/user_editable", method=RequestMethod.GET)
	public String user_editable() {
		return viewName("user_editable") ;
	}
	
	/**
	 * 修改用户账户状态
	 * @param ids
	 * @param lockedStatus
	 * @return
	 */
	@SystemLog(module=BaseConst.MODULE_SYSTEM+"[用户管理]", method="修改用户账户状态")
	@RequestMapping(value="/setUserAccountStatus")
	public @ResponseBody AjaxResponse setUserAccountStatus(Long[] ids, Integer lockedStatus) {
		this.service.setUserAccountStatus(ids, lockedStatus);
		return SpringContextHolder.getBean(AjaxResponse.class).reset() ;
	}
	
	/**
	 * 修改用户编辑状态
	 * @param ids
	 * @param editableStatus
	 * @return
	 */
	@SystemLog(module=BaseConst.MODULE_SYSTEM+"[用户管理]", method="修改用户编辑状态")
	@RequestMapping(value="/setUserEditableStatus")
	public @ResponseBody AjaxResponse setUserEditableStatus(Long[] ids, Integer editableStatus) {
		this.service.setUserEditableStatus(ids, editableStatus);
		return SpringContextHolder.getBean(AjaxResponse.class).reset() ;
	}
	
	/**
	 * 用户添加角色页面
	 * @return
	 */
	@RequestMapping(value="/user_add_role", method=RequestMethod.GET)
	public String user_add_role() {
		return viewName("user_add_role") ;
	}
	
	@SystemLog(module=BaseConst.MODULE_SYSTEM+"[用户管理]", method="为用户添加角色")
	@RequestMapping(value="/addRoleToUser")
	public @ResponseBody AjaxResponse addRoleToUser(Long[] ids, String roleIds) {
		this.service.addRoleToUser(ids, roleIds);
		return SpringContextHolder.getBean(AjaxResponse.class).reset() ;
	}
	
	
	/**
	 * 登录
	 * @param account 账号
	 * @param password 密码
	 * @param captchaCode 验证码
	 * @return
	 */
	@RequestMapping(value="/login", method=RequestMethod.POST)
	public @ResponseBody AjaxResponse login(String account, String password, String captcha) {
		AjaxResponse ajaxResponse = this.service.login(account, password, captcha) ;
		return ajaxResponse ;
	}
	
	/**
	 * 刷新登录页面，判断是否需要显示验证码
	 * @return
	 */
	@RequestMapping(value="/isShowCaptchaCode", method=RequestMethod.GET)
	@ResponseBody
	public AjaxResponse isShowCaptchaCode() {
		AjaxResponse ajaxResponse = SpringContextHolder.getBean(AjaxResponse.class).reset() ;
		ajaxResponse.setStatus(false);
		
		AtomicInteger sessionRetryCount = SystemHelper.getSessionRetryCount();
		if (sessionRetryCount != null) {
			if(sessionRetryCount.get() > 3) {
				ajaxResponse.setMessage("刷新登录页面，需要输入验证码！");
			}
		} else {
			ajaxResponse.setStatus(true);
		}
		
		return ajaxResponse;
	}
	
	/**
	 * 退出系统
	 */
	@RequestMapping(value="/logout", method=RequestMethod.GET)
	public String logout() {
		this.service.logout();
		return InternalResourceViewResolver.REDIRECT_URL_PREFIX+"/manager/login";
	}
	
	
	/**
	 * 找回密码
	 * @param account 账号
	 * @return
	 */
	@RequestMapping(value="/iForgotPassword/{account}/{captchaCode}", method=RequestMethod.GET)
	public @ResponseBody AjaxResponse iForgotPassword(@PathVariable String account, @PathVariable String captchaCode, HttpServletRequest request) {
		AjaxResponse ajaxResponse = SpringContextHolder.getBean(AjaxResponse.class).reset() ;
		if(null == captchaCode || "".equals(captchaCode.trim())) {
			ajaxResponse.setStatus(false);
			ajaxResponse.setMessage("验证码不能为空");
		}
		String code = (String) request.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
		
		if(!captchaCode.equals(code)) {
			ajaxResponse.setStatus(false);
			ajaxResponse.setMessage("验证码不正确，或验证码失效，请点击重新验证码获取！");
		} else {
			ajaxResponse = this.service.iForgotPassword(account) ;
			request.getSession().removeAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
		}
		
		return ajaxResponse ;
	}
	
	/**
	 * 检查连接，跳转到重设密码页面
	 * @param sid
	 * @param username
	 * @return
	 */
	@RequestMapping(value="/checkLink", method=RequestMethod.GET)
	public String checkLink(String sid, String username, Model model) {
		model.addAttribute("resp", this.service.checkResetLink(sid, username)) ;
		return viewName("resetPwd") ;
	}
	
	/**
	 * 重设密码
	 * @param dto(id, account, validateCode, password)
	 * @return
	 */
	@RequestMapping(value="/changePwd")
	public @ResponseBody AjaxResponse changePwd(User dto) {
		return this.service.changePasswordByForgot(dto) ;
	}
	
	/**
	 * 生成验证码
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value="/captchaCode", method=RequestMethod.GET)
	public void captcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
		response.setDateHeader("Expires", 0);
		response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
		response.addHeader("Cache-Control", "post-check=0, pre-check=0");
		response.setHeader("Pragma", "no-cache");
		response.setContentType("image/jpeg");
		String capText = captchaProducer.createText();
		request.getSession().setAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY, capText);
		BufferedImage bi = captchaProducer.createImage(capText);
		ServletOutputStream out = response.getOutputStream();
		ImageIO.write(bi, "jpg", out);
		try {
			out.flush();
		} finally {
			out.close();
		}
	}
}
